#include "SceneManager.h"

#include "Scene.h"

SceneManager* SceneManager::_instance = 0;

///////////////////////////////////////////////////////////
//Constructor & Destructor
///////////////////////////////////////////////////////////


SceneManager::SceneManager() : _window(0), _contextOpenGL(0), _title("Open GL"), _widthWindow(1280), _heightWindow(720), _currentScene(NULL)
{
	SceneModel* scene = new Scene("scene");
	_scenes.insert(std::make_pair<std::string, SceneModel*>("scene", scene));
}

SceneManager::~SceneManager()
{
	//Delete all scene
	std::map<std::string,SceneModel*>::iterator it = _scenes.begin();
	std::map<std::string,SceneModel*>::iterator itEnd = _scenes.end();

	
	for(; it != itEnd; ++it)
	{
		delete(it->second);
	}
	
	_scenes.clear();

	//Delete Singletons
	ShaderManager::DeleteInstance();

	_currentScene = NULL;

	SDL_GL_DeleteContext(_contextOpenGL);
	SDL_DestroyWindow(_window);
	SDL_Quit();
}

//Initialise Window
bool SceneManager::InitialiseWindow()
{

	//Initialise SDL
	if(SDL_Init(SDL_INIT_VIDEO) < 0){
		std::cout << "Error Initialise SDL : " << SDL_GetError() << std::endl;
		SDL_Quit();

		return false;
	}

	//Version OpenGL
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);


	//Double Buffer
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

	//Window Create
	_window = SDL_CreateWindow(_title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _widthWindow, _heightWindow, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
	_contextOpenGL = SDL_GL_CreateContext(_window);

	return true;
}


//InitGL
bool SceneManager::InitGL()
{
#ifdef WIN32

    //Initialise Glew
    GLenum initialisationGLEW(glewInit());

    if(initialisationGLEW != GLEW_OK)
    {
        std::cout << "Error Initialising Glew : " << glewGetErrorString(initialisationGLEW) << std::endl;

		// DSL Quit
        SDL_GL_DeleteContext(_contextOpenGL);
        SDL_DestroyWindow(_window);
        SDL_Quit();

        return false;
    }

#endif
	
	glEnable(GL_DEPTH_TEST);	

    return true;
}


///////////////////////////////////////////////////////////
//Runtime
///////////////////////////////////////////////////////////

void SceneManager::LoadScene(std::string name)
{
	_currentScene = _scenes[name];
	_currentScene->Init();
	//_currentScene = _scenes[name];
}


void SceneManager::Update()
{
	if(_currentScene == NULL)
		return;

	SDL_Event sdl_events;
	
	bool exit = false;

	while(!exit)
	{
		SDL_PollEvent(&sdl_events);

		if(sdl_events.window.event == SDL_WINDOWEVENT_CLOSE)
			exit = true;

		_currentScene->Update(20);
	}
	
}
